package com.example.shop.service.serviceImpl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.shop.mapper.DepartmentMapper;
import com.example.shop.mapper.TaskMapper;
import com.example.shop.mapper.UserDepartmentMapper;
import com.example.shop.pojo.Task;
import com.example.shop.pojo.UserDepartment;
import com.example.shop.service.TaskService;
import com.mysql.cj.util.TimeUtil;

@Service
public class TaskServiceImpl implements TaskService {
	@Autowired
	private TaskMapper taskMapper;
	@Autowired
	private UserDepartmentMapper userDepartmentMapper;

	/**
	 * 添加任务
	 */
	@Override
	public String addTask(List<Task> tasks) {
		String result = "任务添加成功";
		int i = 0;
		for (Task task:tasks) {
			if (task.getTaskDepartment() != null && task.getTaskUser() != null) {
				// 获取该部门所有部员
				List<UserDepartment> uds = userDepartmentMapper.selectByDepartmentId(task.getTaskDepartment());
				List<UserDepartment> ud = uds.stream().filter(ud1 -> ud1.getUserAccount().equals(task.getTaskUser()))
						.collect(Collectors.toList());
				if (uds == null || ud.size() == 0 || ud == null) {
					result = "该部门没有成立或该部员不属于该部门";
					break;
				}
			}
			// 添加任务
			if(taskMapper.add(task)>0) {
				i+=1;
			};
		}
		if(tasks.size() != i) {
			result = "添加任务失败";
		}
		return result;
	}

	/**
	 * 更新任务
	 */
	@Override
	public String updateTask(Task task) {
		// 数据校验
		if (task.getTaskId() == null) {
			return "请先完善信息";
		}
		// 更新任务
		if (taskMapper.updateById(task) <= 0) {
			return "任务更新失败";
		}
		;
		return "任务更新成功";

	}

	/**
	 * 任务查询
	 */
	@Override
	public List<Task> selectTask(Task task) {
		List<Task> tasks = new ArrayList<>();
		// 根据任务人员查询任务
		if (task.getTaskUser() != null) {
			tasks.add(taskMapper.selectByUser(task));
		} else if (task.getTaskDepartment() != null) {
			// 根据部门id查询任务
			tasks.add(taskMapper.selectByDepartment(task));
		} else {
			// 查询所有任务
			
			tasks = taskMapper.selectAll(task);
		}
		return tasks;
	}

	/**
	 * 事件提醒
	 * 
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	@Override
	public String EventSetting(Task task) throws InterruptedException, ExecutionException {
		// 数据校验
		if (task.getTaskId() == null) {
			return "请先完善信息";
		}
		// 获取当前时间和目标时间的时间差（毫秒）
		Long targetTime = task.getTaskRemind().getTime() - System.currentTimeMillis();
		targetTime = Math.max(targetTime, 0);
		// 设置定时任务
		ScheduledFuture<Boolean> scheduleFuture = Executors.newScheduledThreadPool(9).schedule(new Callable() {
			@Override
			public Object call() throws Exception {
				try {// 在这里编写定时执行的任务逻辑
					System.out.println("触发定时任务：" + task.getTaskId());
					// 可以实现具体的提醒功能，如发送提醒通知等
					// 发送短信
					/* SMSUtils.sendMessage("","",user.getPhone(),code); */
					return true;
				} catch (Exception e) {
					return false;
				}
			}

		}, targetTime, TimeUnit.MILLISECONDS);
		// 判断定时任务是否执行成功
		if (!scheduleFuture.get()) {
			return "事件设置异常";
		}
		// 将事件发生时间存入数据库
		if (taskMapper.updateById(task) <= 0) {
			return "设置事件提醒失败";
		}
		;
		return "设置事件提醒成功";

	}
}
